package demoMod.invincibleOne.patches;

import basemod.ReflectionHacks;
import com.evacipated.cardcrawl.modthespire.lib.SpirePatch;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.shop.ShopScreen;
import com.megacrit.cardcrawl.shop.StorePotion;
import com.megacrit.cardcrawl.shop.StoreRelic;
import demoMod.invincibleOne.cards.invincible.MoreIsBetter;
import demoMod.invincibleOne.characters.InvincibleOne;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.stream.Collectors;

public class ShopScreenPatch {
    @SpirePatch(
            clz = ShopScreen.class,
            method = "initPotions"
    )
    public static class PatchInitPotions {
        public static void Postfix(ShopScreen screen) {
            if (AbstractDungeon.player instanceof InvincibleOne) {
                screen.colorlessCards.clear();
                ArrayList<StoreRelic> relics = ReflectionHacks.getPrivate(screen, ShopScreen.class, "relics");
                relics.clear();
                ArrayList<StorePotion> potions = ReflectionHacks.getPrivate(screen, ShopScreen.class, "potions");
                potions.clear();
            }
        }
    }

    @SpirePatch(
            clz = ShopScreen.class,
            method = "initCards"
    )
    public static class PatchInitCards {
        public static void Prefix(ShopScreen screen) {
            if (AbstractDungeon.player instanceof InvincibleOne) {
                while (screen.coloredCards.size() != screen.coloredCards.stream().map(c -> c.cardID).collect(Collectors.toSet()).size()) {
                    screen.coloredCards.sort(Comparator.comparing(o -> o.cardID));
                    for (int i=1;i<screen.coloredCards.size();i++) {
                        if (screen.coloredCards.get(i).cardID.equals(screen.coloredCards.get(i - 1).cardID)) {
                            AbstractCard card = AbstractDungeon.getCardFromPool(AbstractDungeon.rollRarity(), AbstractCard.CardType.ATTACK, true).makeCopy();
                            while (card.cardID.equals(MoreIsBetter.ID)) {
                                card = AbstractDungeon.getCardFromPool(AbstractDungeon.rollRarity(), AbstractCard.CardType.ATTACK, true).makeCopy();
                            }
                            screen.coloredCards.set(i, card);
                        }
                    }
                }
                for (int i=0;i<screen.coloredCards.size();i++) {
                    if (screen.coloredCards.get(i).type == AbstractCard.CardType.POWER) {
                        Collections.swap(screen.coloredCards, i, screen.coloredCards.size() - 1);
                        break;
                    }
                }
            }
        }
    }
}
